<?php

include_once dirname(__FILE__) . "/conf.php";
include_once dirname(__FILE__) . "/error.php";

class Log {
    
    private static $path = ".";
    private static $file = "";
    private static $level = 1;
    private static $log_id = "none";

    const LOG_DEBUG = 1;
    const LOG_ERROR = 2;
    
    public static function init($log_id = "none")
    {
        global $err_code;
        $level = Conf::get("log.level");
        $path = Conf::get("log.path");

        if($level == false || $path == false)
        {
            $err_code = ec_conf_error;
            return false;
        }

        self::$path = (string)$path;
        if(is_writable(self::$path))
        {
            self::$level = $level;
            
            $today = date("Ymd");
            self::$file = self::$path . "/" .  $today . ".log";
            
            self::$log_id = $log_id;
            return true;
        }
        else
        {
            $err_code = ec_perm_error;
            return false;
        }
    }
    
    public static function error($msg)
    {
        $msg = "ERROR " . (string)$msg;
        return self::write_log(self::LOG_ERROR, $msg);
    }
    public static function debug($msg)
    {
        $msg = "DEBUG " . (string)$msg;
        return self::write_log(self::LOG_DEBUG, $msg);
    }
    
    public static function write_log($level, $msg)
    {
        if(strlen(self::$file) > 0 && self::$level <= $level)
        {
            //$now = date("Ymd H:i:s");
            $now = date("H:i:s");
            $one = $now;
            
            $bt = debug_backtrace();
            $stack = $bt[1];
            if(array_key_exists('file', $stack) && array_key_exists('line', $stack))
            {
                $file = basename($stack['file']);
                $line = $stack['line'];
                $one = $one . " " . $file . ":" . $line;
            }

            $one = $one . " " . $msg . " " . self::$log_id . "\n"; 
            file_put_contents(self::$file,  $one, FILE_APPEND | LOCK_EX);
            return true;
        }
        else
        {
            return false;
        }
    }
};

?>
